<template>
  <div class="main-box">
    <TreeFilter
      label="label"
      title="部门列表(单选)"
      :request-api="getDepartmentTree"
      :data="treeFilterData"
      :default-value="initParam.departmentId"
      @change="changeTreeFilter"
    />
    <div class="table-box">
      <ProTable
        ref="proTable"
        row-key="id"
        :indent="20"
        :columns="columns"
        :request-api="queryUserList"
        :request-auto="true"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button type="primary" :icon="CirclePlus" @click="insertDialogVisible = true">新增用户</el-button>
        </template>
        <template #departmentNameList="scope">
          <el-tag v-for="item in scope.row.departmentNameList" type="success" style="margin-right: 5px">{{ item }}</el-tag>
        </template>
        <template #roleNameList="scope">
          <el-tag v-for="item in scope.row.roleNameList" type="warning" style="margin-right: 5px">{{ item }}</el-tag>
        </template>
        <template #jobNameList="scope">
          <el-tag v-for="item in scope.row.jobNameList" type="danger" style="margin-right: 5px">{{ item }}</el-tag>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link :icon="EditPen" @click="openUpdateDialog(scope.row)">编辑</el-button>
          <el-button type="primary" link :icon="View" @click="initPassword(scope.row)">重置密码</el-button>
          <el-button type="primary" v-show="scope.row.status !== 1" link :icon="Refresh" @click="updateUserStatus(scope.row, 1)">
            恢复
          </el-button>
          <!-- <el-button type="primary" v-show="scope.row.status === 1" link :icon="Delete" @click="updateUserStatus(scope.row, -1)">
            禁用
          </el-button> -->
        </template>
      </ProTable>
      <!-- <UserDrawer ref="drawerRef" /> -->
      <!-- <ImportExcel ref="dialogRef" /> -->
      <!-- 新增对话框 -->
      <el-dialog width="45%" v-model="insertDialogVisible" title="新增账户">
        <el-form ref="insertFormRef" :model="insertParam" :rules="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="用户账号" prop="userAccount">
                <el-input v-model="insertParam.userAccount"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户姓名" prop="userName">
                <el-input v-model="insertParam.userName"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="用户性别">
                <el-select v-model="insertParam.userGender">
                  <el-option
                    v-for="item in genderEnum"
                    :key="item.genderValue"
                    :label="item.genderLabel"
                    :value="item.genderValue"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色">
                <el-select multiple v-model="insertParam.roleIdList" placeholder="请选择角色" :options="selectOptions.roleList" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="角色">
                <el-tree-select
                  multiple
                  v-model="insertParam.departmentIdList"
                  placeholder="请选择部门"
                  :data="selectOptions.departmentList"
                  check-strictly
                  :default-expand-all="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="岗位">
                <el-select v-model="insertParam.jobIdList" multiple :options="selectOptions.jobList" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="联系方式">
                <el-input v-model="insertParam.telephone"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="住址">
                <el-input v-model="insertParam.address"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="邮箱">
                <el-input v-model="insertParam.email"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="insertParam.status">
                  <el-radio :label="0" :value="0">禁用</el-radio>
                  <el-radio :label="1" :value="1">正常</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注">
            <el-input v-model="insertParam.remark" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="insertDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="addUser(insertFormRef)">新增</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 修改对话框 -->
      <el-dialog width="45%" v-model="updateDialogVisible" title="修改账户信息">
        <el-form ref="updateFormRef" :model="updateParam" :rules="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="用户账号" prop="userAccount">
                <el-input v-model="updateParam.userAccount"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户姓名" prop="userName">
                <el-input v-model="updateParam.userName"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="用户性别">
                <el-select v-model="updateParam.userGender">
                  <el-option
                    v-for="item in genderEnum"
                    :key="item.genderValue"
                    :label="item.genderLabel"
                    :value="item.genderValue"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色">
                <el-select multiple v-model="updateParam.roleIdList" placeholder="请选择角色" :options="selectOptions.roleList" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="部门">
                <el-tree-select
                  multiple
                  v-model="updateParam.departmentIdList"
                  placeholder="请选择部门"
                  :data="selectOptions.departmentList"
                  check-strictly
                  :default-expand-all="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="岗位">
                <el-select v-model="updateParam.jobIdList" multiple :options="selectOptions.jobList" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="联系方式">
                <el-input v-model="updateParam.telephone"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="住址">
                <el-input v-model="updateParam.address"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="邮箱">
                <el-input v-model="updateParam.email"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="updateParam.status">
                  <el-radio :label="0" :value="0">禁用</el-radio>
                  <el-radio :label="1" :value="1">正常</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注">
            <el-input v-model="updateParam.remark" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="updateDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="updateUser(updateFormRef)">修改</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="tsx" name="accountManage">
import { onMounted, reactive, ref } from "vue";
import { genderType } from "@/utils/dict";
import { useHandleData } from "@/hooks/useHandleData";
import { ElMessage, ElNotification, FormInstance, FormRules } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { CirclePlus, Delete, EditPen, View, Refresh } from "@element-plus/icons-vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { getDepartmentList, getDepartmentTree } from "@/api/modules/auth/department";
import { queryUserList, createUser, editUserStatus, editUserInfo, initUserPassword } from "@/api/modules/auth/user";
import { CreateUserParam, EditUserInfoParam, QueryUserListParam, UserListResult } from "@/api/interface/auth/user";
import { genderEnum, statusEnum, statusFieldNames } from "@/enums/httpEnum";
import { SelectOptionResult, SelectTreeOptionResult } from "@/api/interface";
import { getJobOptions } from "@/api/modules/auth/job";
import { getRoleOptions } from "@/api/modules/auth/role";

const proTable = ref<ProTableInstance>();

const insertFormRef = ref<FormInstance>();

const updateFormRef = ref<FormInstance>();

const treeFilterData = ref<any>([]);

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive<QueryUserListParam>({ departmentId: "" });

const insertDialogVisible = ref(false);

const updateDialogVisible = ref(false);

const selectOptions = reactive<{
  jobList: SelectOptionResult[];
  roleList: SelectOptionResult[];
  departmentList: SelectTreeOptionResult[];
}>({
  jobList: [],
  roleList: [],
  departmentList: []
});

/** 新增参数 */
const insertParam = reactive<CreateUserParam>({
  userAccount: "",
  userName: "",
  userGender: 1,
  status: 1
});

/** 修改用户参数 */
const updateParam = reactive<EditUserInfoParam>({
  userId: "",
  userAccount: "",
  userName: "",
  userGender: 1,
  status: 1
});

const ruleForm = reactive<FormRules>({
  userAccount: [
    { required: true, message: "用户账号不能为空", trigger: "change" },
    {
      pattern: /^[A-Za-z0-9]+$/,
      message: "用户账号只能包含字母和数字",
      trigger: "blur"
    }
  ],
  userName: [{ required: true, message: "用户名不能为空", trigger: "change" }]
});

onMounted(async () => {
  const jobRes = await getJobOptions();
  const roleRes = await getRoleOptions();
  const deptRes = await getDepartmentTree();

  selectOptions.jobList = [...jobRes.data];
  selectOptions.roleList = [...roleRes.data];
  selectOptions.departmentList = [...deptRes.data];
});

// 树形筛选切换
const changeTreeFilter = (val: string) => {
  initParam.departmentId = val;
  proTable.value!.pageable.pageIndex = 1;
  proTable.value!.searchInitParam.departmentId = val;
  proTable.value!.getTableList();
};

// 模拟远程加载性别搜索框数据
const loading = ref(false);
const filterGenderEnum = ref<typeof genderType>([]);
const remoteMethod = (query: string) => {
  filterGenderEnum.value = [];
  if (!query) return;
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    filterGenderEnum.value = genderType.filter(item => item.label.includes(query));
  }, 500);
};

// 表格配置项
const columns = reactive<ColumnProps<UserListResult>[]>([
  { type: "selection", width: 80 },
  { type: "index", label: "#", width: 80 },
  { prop: "userAccount", label: "用户账号", width: 120 },
  { prop: "userName", label: "用户姓名", width: 120 },
  {
    prop: "userGender",
    label: "性别",
    tag: true,
    width: 100,
    enum: [
      { userGenderLabel: "男", userGenderValue: 1 },
      { userGenderLabel: "女", userGenderValue: 2 },
      { userGenderLabel: "未定义", userGenderValue: 3 }
    ],
    fieldNames: { label: "userGenderLabel", value: "userGenderValue" }
  },
  {
    prop: "status",
    label: "用户状态",
    tag: true,
    width: 120,
    enum: statusEnum,
    fieldNames: statusFieldNames
  },
  { prop: "departmentNameList", label: "部门", width: 150 },
  { prop: "roleNameList", label: "角色", width: 150 },
  { prop: "jobNameList", label: "职位", width: 150 },
  { prop: "telephone", label: "联系方式", width: 150 },
  { prop: "email", label: "邮箱", width: 120 },
  { prop: "address", label: "地址", width: 180 },
  { prop: "createDate", label: "创建时间", width: 200 },
  { prop: "operation", label: "操作", fixed: "right", width: 230 }
]);

/** 新增用户 */
const addUser = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await createUser(insertParam);

      insertDialogVisible.value = false;
      ElMessage.success("新增成功");
      proTable.value?.getTableList();
    } else {
      ElMessage.error("请填入必填数据");
    }
  });
};

/** 打开修改对话框 */
const openUpdateDialog = (param: UserListResult) => {
  updateDialogVisible.value = true;
  Object.assign(updateParam, param);
};

/** 修改用户信息 */
const updateUser = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await editUserInfo(updateParam);
      updateDialogVisible.value = false;
      ElMessage.success("修改用户信息成功");
      proTable.value?.getTableList();
    } else {
      ElMessage.error("请填入必填数据");
    }
  });
};

/** 重置用户密码 */
const initPassword = async (param: UserListResult) => {
  await initUserPassword({ userId: param.userId });
  ElMessage.success("重置密码成功");
};

/** 修改用户状态 */
const updateUserStatus = async (param: UserListResult, status: number) => {
  await editUserStatus({ userId: param.userId, status: status });
  ElMessage.success("修改用户状态成功");
};
</script>
